package com.eystar.ext.kit;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;

public class ListKit {

	/**
	 * 抽取List<T> 中的 T对象的 某个属性作为map的key，map的value为 T对象本身。
	 * @param list
	 * @param field
	 * @return
	 */
	public static <K,T> Map<K, T> list2Map(List<T> list,String field){
		Map<K, T> map = new HashMap<K, T>();
		for (T t : list) {
			if (t instanceof Model<?>) {
				 Map<String, K> attrs = Reflect.on(t).field("attrs").get();
				 K k = attrs.get(field);
				 map.put(k, t);
			}else if(t instanceof Record){
				 Map<String, K> attrs = Reflect.on(t).field("columns").get();
				 K k = attrs.get(field);
				 map.put(k, t);
			}else{
				K object = Reflect.on(t).field(field).get();
				map.put(object, t);
			}
		}
		return map;
	}
	
	/**
	 * 抽取List<T> 中T的某个属性，将该属性的值转成 List<M>
	 * @param list
	 * @param field
	 * @return
	 */
	public static <T,M> List<T> list4Pro(List<M> list,String field){
		List<T> ts = new ArrayList<T>();
		for (M m : list) {
			if (m instanceof Model<?>) {
				T t = ((Model<?>) m).get(field);
				ts.add(t);
			}else if(m instanceof Record){
				T t = ((Record) m).get(field);
				ts.add(t);
			}else{
				T t = Reflect.on(m).field(field).get();
				ts.add(t);
			}
		}
		return ts;
	}
	
	public static void main(String[] args) {
		List<Record> records = new ArrayList<Record>();
		
		Record record = new Record();
		record.set("1", "11");
		record.set("2", "22");
		records.add(record);
		
		Record record1 = new Record();
		record1.set("1", "111");
		record1.set("2", "222");
		records.add(record1);
		
		List<String> pros = list4Pro(records, "1");
		System.out.println(pros);
	}
}
